const jsonp = (options) => {
  const script = document.createElement('script')
  let substitute01 = Math.random().toString()
  substitute01 = substitute01.replace('.', '_')
  let substitute02 = Math.random().toString()
  substitute02 = substitute02.replace('.', '_')
  const function_name = `fun${substitute01}_${substitute02}`

  let params = ''
  for (const key in options.data) {
    if (options.data.hasOwnProperty(key)) {
      params += `&${key}=${options.data[key]}`
    }
  }

  // Handle JSONP timeout
  let timeoutOccured = false
  const timeout = setTimeout(() => {
    timeoutOccured = true
    cleanup()
    if (options.error) {
      options.error({
        message: 'Timeout while loading script'
      })
    }
  }, options.timeout || 5000) // Default timeout is 5 seconds

  // Define the global callback function
  window[function_name] = function (response) {
    if (!timeoutOccured) {
      cleanup()
      if (options.success) {
        options.success(response)
      }
    }
  }

  // Set up script source and add to document
  script.src = `${options.url}?callback=${function_name}${params}`
  const body = document.querySelector('body')
  body.appendChild(script)

  // Clean up function
  function cleanup() {
    clearTimeout(timeout)
    delete window[function_name]
    script.remove()
  }

  // Error handling
  script.addEventListener('error', () => {
    if (!timeoutOccured) {
      cleanup()
      if (options.error) {
        options.error({
          message: 'Failed to load script'
        })
      }
    }
  })

  // Clean up on script load
  script.addEventListener('load', () => {
    if (!timeoutOccured) {
      cleanup()
    }
  })
}

export default jsonp
